/*
 * Author: yezi
 * E-mail: okye328@gmail.com
 * Create time: Jan 1, 2013 10:27:58 AM
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
 */
package com.kanbox.linux.operation;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.http.client.methods.HttpUriRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.kanbox.linux.fs.INode;
import com.kanbox.linux.fs.MountPointManager;
import com.kanbox.linux.operation.http.HttpExecutor;
import com.kanbox.linux.operation.http.HttpExecutor.NullInputStream;
import com.kanbox.linux.operation.http.RequestFactory;
import com.kanbox.linux.operation.http.RequestFactory.RequestType;
import com.kanbox.linux.token.TokenManager;

public class FileDownloader implements Runnable {

	private static Logger logger = LoggerFactory
			.getLogger(FileDownloader.class);

	private INode iNode;

	public FileDownloader(INode iNode) {
		this.iNode = iNode;
	}

	public File downLoad() throws IOException {
		File newFile = new File(MountPointManager.remoteToLocalDataPath(iNode
				.getFullPath()));
		File parentDir = new File(newFile.getParent());
		parentDir.mkdirs();
		if (newFile.exists() && newFile.length() == iNode.getFileSize()
				&& newFile.lastModified() == iNode.getModificationDate()) {
			return newFile;// ignore
		}

		HttpUriRequest request = RequestFactory.buildHTTPRequest(
				RequestFactory.DOWNLOAD, iNode.getFullPath(), RequestType.GET,
				TokenManager.getAccessToken());
		InputStream in = HttpExecutor.executeForStream(request);
		if (in instanceof NullInputStream) {
			newFile.delete();
			newFile.createNewFile();
			newFile.setLastModified(iNode.getModificationDate());
			in.close();
			return newFile;
		}
		FileOutputStream fos = new FileOutputStream(newFile);
		byte[] buffer = new byte[1024];
		int count = 0;
		int temp = 0;
		NetworkMeter nm = new NetworkMeter("Downloading " + iNode.getFullPath());
		new Thread(nm).start();
		while ((temp = in.read(buffer)) != -1) {
			count += temp;
			fos.write(buffer, 0, temp);
			nm.addDataCount(temp);
		}
		nm.setToStop(true);
		fos.close();
		in.close();
		newFile.setLastModified(iNode.getModificationDate());

		if (count != iNode.getFileSize())
			throw new IOException("Not read full file!");
		return newFile;
	}

	@Override
	public void run() {
		try {
			downLoad();
		} catch (IOException e) {
			logger.error("Error when downloading file", e);
		}
	}
}
